#include "TUIBase.h"
#include "uart.h"

//static int timeCount = 0;

int uartTask()
{ 
  int nread,count=0,recvNum = 0;
  unsigned char mesgType = UART_TUI;
  char buff[RD_BUF_SIZE],isFinish = 1;
  char packBuff[RD_BUF_SIZE];

  while(allRun_flag)
  {
    int buff_length = readUART(&(buff[count]),RD_BUF_SIZE);
    if(isFinish == 1 && buff_length > 0)//the pre buffer is finished
    {
      if(buff_length>3 && buff[0] == 0x5a && buff[1] == 0xa5) //TUI message
        mesgType = UART_TUI;
      else
        mesgType = UART_CMD;


      if( mesgType == UART_TUI && buff_length < (buff[2] + 3) && buff_length > 0)
        isFinish = 0;
      else if(mesgType == UART_CMD && buff[buff_length-1] != '\n' && buff[buff_length-1] !='\0')
        isFinish = 0;

      count = buff_length;
    }
    else if(buff_length > 0)
    {
      if( mesgType == UART_TUI && buff_length + count < buff[2] + 3 && buff_length >0) //the current buffer still not finished
      {
        count += buff_length;
      }
      else if(mesgType == UART_CMD && buff[buff_length-1] != '\n' && buff[buff_length-1] !='\0')
      {
        count += buff_length;
      }
      else if(buff_length >0)// the current buffer finished
      {
        count +=buff_length;
        isFinish = 1;
      }
    }


    if(count> 0 && isFinish ==1) //receive the whole command
    {

      if(mesgType == UART_TUI)
        TUI_appendCmd(buff,count);
      else if(mesgType == UART_CMD)
      {
        strncpy(buff+count,"\0",1);
        mLog("recv buffer:%s\n",buff);
        packet_append(DRTB_PORT, buff, count);
      }
      count = 0;
    }
/*
    timeCount++;
    if(timeCount > 2000)
      timeCount = 1;
    //---------TUI related----------------------
    if(timeCount % 500 == 0)
    {
      TUI_readStatus();
      if(packet_read(DRTC_PORT,packBuff,RD_BUF_SIZE) > 0)
      {
        TUI_packetParse(packBuff, strlen(packBuff));
        TUI_dispAllStatus();
        //TUI_updateMethodStatus();
      }
    }
    if(timeCount % 2000 == 0)
      TUI_updateInfo();
*/
    recvNum = TUI_readAns(packBuff,RD_BUF_SIZE);
    if(recvNum > 0)
      writeUART(packBuff,recvNum);
    //--------uart cmd related-----------------
    recvNum = packet_read(DRTB_PORT,packBuff,RD_BUF_SIZE);
    if(recvNum > 0)
      writeUART(packBuff,recvNum);
    Task_yield();
  }
  closeUART();
  return 0;
}

